<template>
  <div class="ai-chat">
    <!-- 顶部导航 -->
    <div class="header">
      <div class="back" @click="goBack">＜</div>
      <div class="title">快速问诊</div>
      <div class="notification-icon">🔔</div>
      <div class="notification">

      </div>
    </div>

    <!-- 聊天内容区域 -->
    <div class="chat-container" ref="chatContainer">
      <!-- AI欢迎消息 -->
      <div class="message ai-message">
        <div class="message-content">
          你好，请详细描述您的病情，我们将会安排适合的医生为你服务
        </div>
      </div>

      <!-- 快速选择按钮 -->
      <div class="quick-replies">
        <div class="quick-reply-hint">您也可以点击标签快速回答：</div>
        <!-- 快速回答标签组 - 这部分是从后端返回的数据 -->
        <div class="tags">
          <div
              v-for="tag in quickReplyTags"
              :key="tag.id"
              class="tag-item"
              @click="selectQuickReply(tag.symptomName)"
          >
            {{ tag.symptomName }}
          </div>
        </div>
      </div>

        <!-- 聊天记录 -->
        <div
            v-for="(msg, index) in chatMessages"
            :key="index"
            class="message"
            :class="msg.type === 'user' ? 'user-message' : 'ai-message'"
        >
          <div class="message-content">{{ msg.content }}</div>
        </div>
    </div>

    <!-- 底部输入区域 -->
    <div class="input-area">
      <div class="input-box">
        <input
            v-model="inputMessage"
            type="text"
            placeholder="描述越细，推荐越准，至少2个字"
            @keyup.enter="sendMessage"
        >
        <div class="send-btn" @click="sendMessage">发送</div>
        <el-button
          type="primary"
          :disabled="!isRegistered"
          class="visit-btn"
          @click="handleVisit"
        >
          就诊
        </el-button>
      </div>

      <!-- 底部功能按钮 -->
      <div class="action-buttons">

      </div>
    </div>
  </div>
</template>

<script>
import { querySymptomList } from "@/api/symptom/symptom.js";

export default {
  name: 'AiChat',

  data() {
    return {
      inputMessage: '',
      hasNewMessage: false,
      chatMessages: [], // 直接初始化为空数组
      quickReplyTags: [],
      eventSource: null,
      organId: null,
      // 添加新的数据属性来存储医生信息
      currentDoctor: {
        name: null,
        price: null
      },
      isRegistered: false, // 添加挂号状态控制
    }
  },
  created() {
    this.getQuickReplyTags()
    // 检查是否是从支付页面返回
    const isFromPayment = this.$route.query.fromPayment === 'true'

    if (isFromPayment) {
      // 从支付页面返回，恢复聊天记录
      const savedChat = localStorage.getItem('chatHistory')
      if (savedChat) {
        const chatData = JSON.parse(savedChat)
        this.chatMessages = chatData.messages  // 从 messages 字段获取聊天记录
        localStorage.removeItem('chatHistory')
      }
    }
  },
  methods: {
    async getQuickReplyTags() {
      try {
        let partId =this.$route.query.partId;
        // 从后端获取快速回复标签
        querySymptomList(partId).then(res => {
          console.log("返回的数据: ",res)
          this.quickReplyTags = res
        })
      } catch (error) {
        console.error('获取快速回复标签失败：', error)
      }
    },
    // 滚动到底部
    async scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.chatContainer
        if (container) {
          container.scrollTop = container.scrollHeight
        }
      })
    },

    // 选择快速回复
    async selectQuickReply(tag) {
      this.inputMessage = tag
      await this.sendMessage()

    },

    // ... existing code ...

    async sendMessage() {
      if (!this.inputMessage.trim()) {
        this.$message.error('请输入内容')
        return
      }

      // 添加用户消息
      this.chatMessages.push({
        type: 'user',
        content: this.inputMessage
      })

      const message = this.inputMessage
      this.inputMessage = ''
      await this.scrollToBottom()

      try {
        // 添加一个空的 AI 消息
        this.chatMessages.push({
          type: 'ai',
          content: ''
        })

        // 获取最新添加的 AI 消息的引用
        const currentAiMessage = this.chatMessages[this.chatMessages.length - 1]

        // 创建 EventSource 连接
        const eventSource = new EventSource(`/dev-api/ai/ai/chat?message=${encodeURIComponent(message)}`)

        eventSource.onmessage = (event) => {
          if (event.data === '[complete]') {
            eventSource.close()
            const aiResponse = currentAiMessage.content

            console.log('----------------------------------------')
            console.log('完整的AI回复内容:', aiResponse)

            // 检查是否包含挂号成功的信息
            const isSuccess = aiResponse.includes('挂号成功') ||
                             aiResponse.includes('预约成功') ||
                             aiResponse.includes('成功挂上了')
            console.log('是否包含成功信息:', isSuccess)

            if (isSuccess) {
              // 向前查找最近的包含医生信息的消息
              let doctorName = null;
              let price = null;

              // 遍历所有消息查找医生信息
              console.log('开始查找医生信息...')
              for (let i = this.chatMessages.length - 1; i >= 0; i--) {
                const msg = this.chatMessages[i].content;
                console.log(`检查消息 ${i}:`, msg)

                if (msg && typeof msg === 'string') {
                  // 修改正则表达式匹配模式
                  let doctorNameMatch = msg.match(/医生姓名：([^，。\n]+)/) ||
                                       msg.match(/医生：([^，。\n]+)/) ||
                                       msg.match(/([^，。\n]+)医生/);

                  let priceMatch = msg.match(/挂号费用：(\d+(?:\.\d+)?)/) ||
                                  msg.match(/费用：(\d+(?:\.\d+)?)/) ||
                                  msg.match(/(\d+(?:\.\d+)?)元/);

                  console.log('名字匹配结果:', doctorNameMatch)
                  console.log('价格匹配结果:', priceMatch)

                  if (doctorNameMatch && priceMatch) {
                    doctorName = doctorNameMatch[1].trim();
                    price = priceMatch[1];
                    this.isRegistered = true; // 设置挂号状态
                    console.log('找到医生信息:', { doctorName, price })
                    break;
                  }
                }
              }

              if (doctorName && price) {
                console.log('准备显示支付确认框')
                this.saveChatHistory();
                this.$confirm('挂号已确认，是否立即前往支付？', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'success'
                }).then(() => {
                  console.log('用户确认支付')
                  const traceNo = Math.floor(Math.random() * 900000) + 100000;
                  const payUrl = `http://127.0.0.1:9201/pay/pay?subject=${encodeURIComponent(doctorName)}&traceNo=${traceNo}&totalAmount=${price}`;
                  console.log('支付链接:', payUrl)
                  window.open(payUrl, '_self');
                }).catch(() => {
                  this.$message({
                    type: 'info',
                    message: '您可以稍后在订单中心完成支付'
                  });
                });
              } else {
                console.error('未找到医生信息，doctorName:', doctorName, 'price:', price)
                this.$message.error('未找到医生信息，请重试')
              }
            }
            return;
          }

          // 累积消息内容
          currentAiMessage.content += event.data;
          this.scrollToBottom();
        }

        eventSource.onerror = (error) => {
          console.error('SSE错误:', error)
          eventSource.close()
          if (!currentAiMessage.content) {
            currentAiMessage.content = '发送失败，请重试'
          }
          this.scrollToBottom()
        }

      } catch (error) {
        console.error('发送消息失败:', error)
        this.chatMessages.push({
          type: 'ai',
          content: '发送失败，请重试'
        })
        this.scrollToBottom()
      }

    },
// 修改保存聊天记录的方法
    saveChatHistory() {
      // 保持与 getChatHistory 方法期望的数据结构一致
      localStorage.setItem('chatHistory', JSON.stringify({
          messages: this.chatMessages,
          timestamp: new Date().getTime()
      }))
    },

    // 添加获取聊天记录的方法
    getChatHistory() {
      const savedChat = localStorage.getItem('chatHistory')
      if (savedChat) {
        const chatData = JSON.parse(savedChat)
        // 24小时后过期
        const isExpired = (new Date().getTime() - chatData.timestamp) > 24 * 60 * 60 * 1000

        if (!isExpired) {
          return chatData.messages
        } else {
          localStorage.removeItem('chatHistory')
        }
      }
      return null
    },
// ... existing code ...

    // 返回上一页
    goBack() {
      console.log('返回按钮')
      this.$router.back()
    },

    // 其他功能
    showHistory() {
      this.$message.info('查看历史记录')
    },

    startVoiceInput() {
      this.$message.info('开始语音输入')
    },

    uploadImage() {
      this.$message.info('上传图片')
    },

    // 添加就诊处理方法
    handleVisit() {
      this.$confirm('确定要开始就诊吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // TODO: 处理就诊逻辑
        // 跳转到处方页面

        this.$router.push({
          path: '/prescription',
          query: {
            doctorName: this.currentDoctor.name,
            fromChat: 'true'
          }
        });
        this.$message.success('开始就诊')
      }).catch(() => {})
    },

  },



  // 组件销毁时关闭 EventSource 连接
  beforeDestroy() {
    if (this.eventSource) {
      this.eventSource.close()
      this.eventSource = null
    }
  }
}
</script>

<style scoped lang="scss">
.ai-chat {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f7f8fa;

  .header {
    height: 44px;
    background-color: #4a90e2;
    color: white;
    display: flex;
    align-items: center;
    padding: 0 16px;
    position: relative;

    .back {
      font-size: 20px;
      padding: 8px;
      margin-left: -8px;
    }

    .title {
      flex: 1;
      text-align: center;
      font-size: 18px;
    }

    .notification {
      padding: 8px;
      margin-right: -8px;
    }
  }

  .chat-container {
    flex: 1;
    overflow-y: auto;
    padding: 16px;
    background-color: #f5f5f5;

    .message {
      margin-bottom: 16px;

      .message-content {
        max-width: 70%;
        padding: 12px 16px;
        border-radius: 16px;
        font-size: 14px;
        line-height: 1.5;
      }
    }

    .ai-message {
      .message-content {
        background-color: white;
        margin-right: auto;
      }
    }

    .user-message {
      display: flex;
      justify-content: flex-end;

      .message-content {
        background-color: #4a90e2;
        color: white;
      }
    }
  }

  .quick-replies {
    margin: 20px 0;

    .quick-reply-hint {
      color: #666;
      font-size: 14px;
      margin-bottom: 12px;
    }

    .tags {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;

      .tag-item {
        background-color: white;
        padding: 8px 16px;
        border-radius: 20px;
        font-size: 14px;
        color: #4a90e2;
        border: 1px solid #4a90e2;
        cursor: pointer;

        &:active {
          opacity: 0.8;
        }
      }
    }
  }

  .input-area {
    background-color: white;
    padding: 12px 16px;
    border-top: 1px solid #eee;

    .input-box {
      display: flex;
      align-items: center;
      background-color: #f5f5f5;
      border-radius: 4px;
      padding: 8px 12px;
      margin-bottom: 12px;

      input {
        flex: 1;
        border: none;
        background: none;
        font-size: 14px;
        padding: 0;
        margin: 0;
        outline: none;

        &::placeholder {
          color: #999;
        }
      }

      .send-btn {
        color: #4a90e2;
        font-size: 14px;
        padding: 4px 8px;
        cursor: pointer;

        &:active {
          opacity: 0.8;
        }
      }

      .visit-btn {
        margin-left: 10px;
        height: 32px;
      }
    }

    .quick-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
    }

    .action-buttons {
      display: flex;
      justify-content: space-around;

      .action-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        font-size: 12px;
        color: #666;
        cursor: pointer;



        &:active {
          opacity: 0.8;
        }
      }
    }
  }

  .doctor-list {
    margin: 20px 0;
    padding: 16px;
    background-color: white;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    .doctor-list-title {
      font-size: 16px;
      font-weight: bold;
      color: #333;
      margin-bottom: 16px;
    }

    .doctor-cards {
      display: flex;
      flex-direction: column;
      gap: 16px;
    }

    .doctor-card {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px;
      background-color: #f8f9fa;
      border-radius: 8px;
      border: 1px solid #eee;

      .doctor-info {
        flex: 1;

        .doctor-name {
          font-size: 16px;
          font-weight: bold;
          color: #333;
          margin-bottom: 4px;
        }

        .doctor-title {
          font-size: 14px;
          color: #666;
          margin-bottom: 4px;
        }

        .doctor-specialty {
          font-size: 14px;
          color: #4a90e2;
        }
      }

      .doctor-action {
        margin-left: 16px;

        .consult-btn {
          padding: 8px 16px;
          background-color: #4a90e2;
          color: white;
          border: none;
          border-radius: 20px;
          font-size: 14px;
          cursor: pointer;
          transition: all 0.3s ease;

          &:hover {
            background-color: #357abd;
          }
        }
      }
    }
  }
}
</style>
